﻿@using WindowsAuth.models;
@using Microsoft.AspNetCore.Http;

@{
    ViewData["Title"] = "Home";
}

@if (ViewData["isAuthorized"] != null && !(bool)ViewData["isAuthorized"])
{
    <script>
        var ALERT_TITLE = "Alert";
        var ALERT_BUTTON_TEXT = "Join SG";
        var AddGroupLink = "@ViewData["AddGroupLink"]";

        if (document) {
            window.alert = function (txt) {
                createCustomAlert(txt);
            }
        }

        //create a customize alert
        function createCustomAlert(txt) {
            d = document;

            if (d.getElementById("modalContainer")) return;

            mObj = d.getElementsByTagName("body")[0].appendChild(d.createElement("div"));
            mObj.id = "modalContainer";

            alertObj = mObj.appendChild(d.createElement("div"));
            alertObj.id = "alertBox";
            if (d.all && !window.opera) alertObj.style.top = document.documentElement.scrollTop + "px";
            alertObj.style.visiblity = "visible";

            h1 = alertObj.appendChild(d.createElement("h1"));
            h1.appendChild(d.createTextNode(ALERT_TITLE));
            closeBtn = alertObj.appendChild(d.createElement("button"));
            closeBtn.innerHTML = "X";
            closeBtn.style.float = "right";
            closeBtn.style.color = "red";
            closeBtn.onclick = function () { removeCustomAlertInLink(); return false;}
            h1.append(closeBtn)

            msg = alertObj.appendChild(d.createElement("p"));
            msg.innerHTML = txt;

            btn = alertObj.appendChild(d.createElement("a"));
            btn.id = "closeBtn";
            btn.appendChild(d.createTextNode(ALERT_BUTTON_TEXT));
            btn.href = "#";
            btn.focus();
            btn.onclick = function () { removeCustomAlert(); return false; }


            alertObj.style.display = "block";

        }


        function removeCustomAlert() {
            removeCustomAlertInLink();
            window.open(AddGroupLink,"_blank");
        }

        function removeCustomAlertInLink() {
            document.getElementsByTagName("body")[0].removeChild(document.getElementById("modalContainer"));
        }
        alert("You are not an authorized user for this cluster. Please request to join a security group by following the button below.");
    </script>
 }


@if (ViewData["isAuthorized"] != null && (bool)ViewData["isAuthorized"])
{
    <div class="row">
        <h2>Welcome to Deep Learning Training Service, @ViewData["Username"] !</h2>
        <span class="label label-default">Cluster Resource</span>
        <table id="cluster_status" class="table table-bordered table-condensed table-hover table-striped">
            <thead>
                <tr>
                    <th>Name</th>
                    <th>Total GPU</th>
                    <th>Reserved GPU</th>
                    <th>Used GPU</th>
                    <th>Available GPU</th>
                    <th>Active Jobs</th>
                </tr>
            </thead>
            <tbody></tbody>
        </table>
        <span class="label label-default">Cluster Storage</span>
        <table id="cluster_storage" class="table table-bordered table-condensed table-hover table-striped">
            <thead>
                <tr>
                    <th>Name</th>
                    <th>Work Directory</th>
                    <th>Data Directory</th>
                </tr>
            </thead>
            <tbody></tbody>
        </table>
    </div>
}
else
{

    <div id="myCarousel" class="carousel slide" data-ride="carousel" data-interval="6000">
        <div class="carousel-inner" role="listbox">
            <div class="item active">
                <img src="~/images/banner1.jpg" width="100%" alt="ASP.NET" class="img-responsive" />
                <div class="carousel-caption" role="option">
                    <p>
                        Welcome to Deep Learning Training Service!
                    </p>
                </div>
            </div>
        </div>
    </div>
}

<script type="text/javascript">

    var app = angular.module('indexApp', ["xeditable"]);

    app.run(function (editableOptions) {
        editableOptions.theme = 'bs3';
    });

    var tolist = function (info) {
        if (typeof info === 'string' || info instanceof String)
            return [info];
        else if (info)
            return info;
        else
            return [];
    };

    app.controller('indexCtrl', function ($scope, $log) {
        var info = '@ViewData["Dashboard"]';
        var infoByteArray = window.atob(info);
        var toshow = $scope.$eval(infoByteArray);
        $scope.dashboard = {};
        for (var key in toshow)
        {
            if (!(toshow[key].hasOwnProperty("supress")) && toshow[key].hasOwnProperty("servers") )
            {
                $scope.dashboard[key] = toshow[key];
                var server = tolist(toshow[key]["servers"])[0];
                var url = "http://" + server;
                if ($scope.dashboard[key]["https"])
                    url = "https://" + server;
                if ($scope.dashboard[key]["port"])
                    url += ":" + $scope.dashboard[key]["port"];
                $scope.dashboard[key]["url"] = url;
            }
        };
        $log.log($scope.dashboard);
    });
</script>

@if (ViewData["isAuthorized"] != null && (bool)ViewData["isAuthorized"])
{
    <script>
        var clusters = @Html.Raw(@Context.Session.GetString("TeamClusters"));
        var clustersInfo = Object.create(null);
        var clustersStorage = Object.create(null);

        function totalOf(value) {
            if (typeof value === 'number') return value < 0 ? 0 : value;
            var total = 0;
            $.each(value, function (key, value) {
                total += value;
            });
            return total < 0 ? 0 : total;
        }

        function buildClusterTable() {
            $.when.apply($, $.map(clusters, function (cluster) {
                return $.ajax({
                    url: '/api/dlws/GetVC',
                    data: { cluster: cluster, vcName: '@Context.Session.GetString("Team")' },
                    dataType: 'json',
                    timeout: 10000
                }).then(function (data) {
                    return data;
                }).catch (function () {
                    return;
                });
            })).then(function () {
                var cluster = null
                var args = [].slice.call(arguments);
                $.each(clusters, function (index) {
                    if (args[index]) {
                        clustersInfo[this] = args[index];
                        if (cluster == null) {
                            cluster = this.valueOf()
                        }
                    }
                });


                $("#cluster_status").find("tr:gt(0)").remove();
                $.each(clustersInfo, function (name, json) {
                    var tr;
                    //Append each row to html table
                    tr = $('<tr/>');
                    tr.append("<td>" + name + "</td>");
                    tr.append("<td>" + totalOf(json.gpu_capacity) + "</td>");
                    tr.append("<td>" + totalOf(json.gpu_unschedulable) + "</td>");
                    tr.append("<td>" + totalOf(json.gpu_used) + "</td>");
                    tr.append("<td>" + totalOf(json.gpu_avaliable) + "</td>");
                    tr.append("<td>" + totalOf(json.AvaliableJobNum) + "</td>");
                    $('#cluster_status').append(tr);
                })
            })
        }
        function buildStorageTable() {
            $.when.apply($, $.map(clusters, function (cluster) {
                return $.ajax({
                    url: '/api/dlws/GetMountPoints',
                    data: { cluster: cluster },
                    dataType: 'json',
                    timeout: 10000
                }).then(function (data) {
                    return data;
                }).catch(function () {
                    return;
                });
            })).then(function () {
                var cluster = null
                var args = [].slice.call(arguments);
                $.each(clusters, function (index) {
                    if (args[index]) {
                        clustersStorage[this] = args[index];
                        if (cluster == null) {
                            cluster = this.valueOf()
                        }
                    }
                });

                $("#cluster_storage").find("tr:gt(0)").remove();
                $.each(clustersStorage, function (name, json) {
                    var tr;
                    var workPath = filter(json.workPath);
                    var dataPath = filter(json.dataPath);
                    //Append each row to html table
                    tr = $('<tr/>');
                    tr.append("<td>" + name + "</td>");
                    tr.append("<td>" + "<a href=" + workPath +">" + filter(json.workPath) + "</a>" + "</td>");
                    tr.append("<td>" + "<a href=" + dataPath +">" + filter(json.dataPath) + "</a>" + "</td>");

                    $('#cluster_storage').append(tr);
                })
            })
        }
        function filter(path) {
            return path.replace(/^file:/, "").replace(/\//g, "\\");
        }
        buildClusterTable();
        buildStorageTable();

    </script>
}
<style>
#modalContainer {
	background-color:rgba(0, 0, 0, 0.3);
	position:absolute;
	width:100%;
	height:100%;
	top:0px;
	left:0px;
	z-index:10000;
    display:flex;
    justify-content:center;
    align-items:center;
 /* required by MSIE to prevent actions on lower z-index elements */
}

#alertBox {
	position:relative;
	width:400px;
	min-height:100px;
	border:1px solid #666;
	background-color:#fff;
	background-repeat:no-repeat;
	background-position:20px 30px;
}

    #alertBox h1 {
        margin: 0;
        font: bold 0.9em verdana,arial;
        background-color: #357EBD;
        color: #FFF;
        padding: 2px 0 3px 5px;
    }

#alertBox p {
  font: 1.1em verdana,arial;
  height: 60px;
  padding:10px;
  text-align: center;
}

#alertBox #closeBtn {
	display:inline-block;
	position:relative;
	margin:15px 38%;
	padding:7px;
	border:0 none;
	width:24%;
	font:0.7em verdana,arial;
	text-transform:uppercase;
	text-align:center;
	color:#FFF;
	background-color:#357EBD;
	border-radius: 3px;
	text-decoration:none;

}
</style>
<!--
<div id= "myCarousel" class="carousel slide" data- ride="carousel" data- interval="6000" >
        <ol class="carousel-indicators">
            <li data-target="#myCarousel" data-slide-to="0" class="active"></li>
            <li data-target="#myCarousel" data-slide-to="1"></li>
            <li data-target="#myCarousel" data-slide-to="2"></li>
            <li data-target="#myCarousel" data-slide-to="3"></li>
        </ol>
        <div class="carousel-inner" role="listbox">
            <div class="item active">
                <img src="~/images/banner1.svg" alt="ASP.NET" class="img-responsive" />
                <div class="carousel-caption" role="option">
                    <p>
                        Learn how to build ASP.NET apps that can run anywhere.
                    <a class="btn btn-default" href="http://go.microsoft.com/fwlink/?LinkID=525028&clcid=0x409">
                            Learn More
                    </a>
                    </p>
                </div>
            </div>
            <div class="item">
                <img src="~/images/banner2.svg" alt="Visual Studio" class="img-responsive" />
                <div class="carousel-caption" role="option">
                    <p>
                        There are powerful new features in Visual Studio for building modern web apps.
                    <a class="btn btn-default" href="http://go.microsoft.com/fwlink/?LinkID=525030&clcid=0x409">
                            Learn More
                    </a>
                    </p>
                </div>
            </div>
            <div class="item">
                <img src="~/images/banner3.svg" alt="Package Management" class="img-responsive" />
                <div class="carousel-caption" role="option">
                    <p>
                        Bring in libraries from NuGet, Bower, and npm, and automate tasks using Grunt or Gulp.
                    <a class="btn btn-default" href="http://go.microsoft.com/fwlink/?LinkID=525029&clcid=0x409">
                            Learn More
                    </a>
                    </p>
                </div>
            </div>
            <div class="item">
                <img src="~/images/banner4.svg" alt="Microsoft Azure" class="img-responsive" />
                <div class="carousel-caption" role="option">
                    <p>
                        Learn how Microsoft's Azure cloud platform allows you to build, deploy, and scale web apps.
                    <a class="btn btn-default" href="http://go.microsoft.com/fwlink/?LinkID=525027&clcid=0x409">
                            Learn More
                    </a>
                    </p>
                </div>
            </div>
        </div>
        <a class="left carousel-control" href="#myCarousel" role="button" data-slide="prev">
            <span class="glyphicon glyphicon-chevron-left" aria-hidden="true"></span>
            <span class="sr-only">Previous</span>
        </a>
        <a class="right carousel-control" href="#myCarousel" role="button" data-slide="next">
            <span class="glyphicon glyphicon-chevron-right" aria-hidden="true"></span>
            <span class="sr-only">Next</span>
        </a>
</div >

        <div class="row">
            <div class="col-md-3">
                <h2>Application uses</h2>
                <ul>
                    <li>Sample pages using ASP.NET Core MVC</li>
                    <li><a href="http://go.microsoft.com/fwlink/?LinkId=518004">Bower</a> for managing client-side libraries</li>
                    <li>Theming using <a href="http://go.microsoft.com/fwlink/?LinkID=398939">Bootstrap</a></li>
                </ul>
            </div>
            <div class="col-md-3">
                <h2>How to</h2>
                <ul>
                    <li><a href="http://go.microsoft.com/fwlink/?LinkID=398600">Add a Controller and View</a></li>
                    <li><a href="http://go.microsoft.com/fwlink/?LinkID=699562">Add an appsetting in config and access it in app.</a></li>
                    <li><a href="http://go.microsoft.com/fwlink/?LinkId=699315">Manage User Secrets using Secret Manager.</a></li>
                    <li><a href="http://go.microsoft.com/fwlink/?LinkId=699316">Use logging to log a message.</a></li>
                    <li><a href="http://go.microsoft.com/fwlink/?LinkId=699317">Add packages using NuGet.</a></li>
                    <li><a href="http://go.microsoft.com/fwlink/?LinkId=699318">Add client packages using Bower.</a></li>
                    <li><a href="http://go.microsoft.com/fwlink/?LinkId=699319">Target development, staging or production environment.</a></li>
                </ul>
            </div>
            <div class="col-md-3">
                <h2>Overview</h2>
                <ul>
                    <li><a href="http://go.microsoft.com/fwlink/?LinkId=518008">Conceptual overview of what is ASP.NET Core</a></li>
                    <li><a href="http://go.microsoft.com/fwlink/?LinkId=699320">Fundamentals of ASP.NET Core such as Startup and middleware.</a></li>
                    <li><a href="http://go.microsoft.com/fwlink/?LinkId=398602">Working with Data</a></li>
                    <li><a href="http://go.microsoft.com/fwlink/?LinkId=398603">Security</a></li>
                    <li><a href="http://go.microsoft.com/fwlink/?LinkID=699321">Client side development</a></li>
                    <li><a href="http://go.microsoft.com/fwlink/?LinkID=699322">Develop on different platforms</a></li>
                    <li><a href="http://go.microsoft.com/fwlink/?LinkID=699323">Read more on the documentation site</a></li>
                </ul>
            </div>
            <div class="col-md-3">
                <h2>Run & Deploy</h2>
                <ul>
                    <li><a href="http://go.microsoft.com/fwlink/?LinkID=517851">Run your app</a></li>
                    <li><a href="http://go.microsoft.com/fwlink/?LinkID=517853">Run tools such as EF migrations and more</a></li>
                    <li><a href="http://go.microsoft.com/fwlink/?LinkID=398609">Publish to Microsoft Azure Web Apps</a></li>
                </ul>
            </div>
        </div>
    -->
